'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = removeMany;

var _helpers = require('./helpers');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function removeMany(model, tc, opts) {
  if (!model || !model.modelName || !model.schema) {
    throw new Error('First arg for Resolver removeMany() should be instance of Mongoose Model.');
  }

  if (!tc || tc.constructor.name !== 'TypeComposer') {
    throw new Error('Second arg for Resolver removeMany() should be instance of TypeComposer.');
  }

  const outputTypeName = `RemoveMany${tc.getTypeName()}Payload`;
  const outputType = tc.constructor.schemaComposer.getOrCreateTC(outputTypeName, t => {
    t.addFields({
      numAffected: {
        type: 'Int',
        description: 'Affected documents number'
      }
    });
  });

  const resolver = new tc.constructor.schemaComposer.Resolver({
    name: 'removeMany',
    kind: 'mutation',
    description: 'Remove many documents without returning them: ' + 'Use Query.remove mongoose method. ' + 'Do not apply mongoose defaults, setters, hooks and validation. ',
    type: outputType,
    args: (0, _extends3.default)({}, (0, _helpers.filterHelperArgs)(tc, model, (0, _extends3.default)({
      filterTypeName: `FilterRemoveMany${tc.getTypeName()}Input`,
      isRequired: true,
      model
    }, opts && opts.filter))),
    resolve: (() => {
      var _ref = (0, _asyncToGenerator3.default)(function* (resolveParams) {
        const filterData = resolveParams.args && resolveParams.args.filter || {};

        if (!(typeof filterData === 'object') || Object.keys(filterData).length === 0) {
          throw new Error(`${tc.getTypeName()}.removeMany resolver requires at least one value in args.filter`);
        }

        resolveParams.query = model.find();
        (0, _helpers.filterHelper)(resolveParams);
        resolveParams.query = resolveParams.query.remove();

        let res;

        // `beforeQuery` is experemental feature, if you want to use it
        // please open an issue with your use case, cause I suppose that
        // this option is excessive
        if (resolveParams.beforeQuery) {
          res = yield resolveParams.beforeQuery(resolveParams.query, resolveParams);
        } else {
          res = yield resolveParams.query.exec();
        }

        if (res.ok) {
          // mongoose 5
          return {
            numAffected: res.n
          };
        } else if (res.result && res.result.ok) {
          // mongoose 4
          return {
            numAffected: res.result.n
          };
        }
        // unexpected response
        throw new Error(JSON.stringify(res));
      });

      return function resolve(_x) {
        return _ref.apply(this, arguments);
      };
    })()
  });

  return resolver;
}
/* eslint-disable no-param-reassign */